package com.example.charlotte.snakegame;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.preference.PreferenceManager;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by Charlotte on 2018/12/7.
 */

public class GameMusic{
    private SharedPreferences saved;
    static final int GAME_MUSIC = 0;
    static final int EAT_MUSIC = 1;
    static final int OVER_MUSIC = 2;
    static final int BTN_MUSIC = 3;
    private SoundPool soundPool;
    private HashMap<Integer, Integer> soundmap = new HashMap<>();
    private MediaPlayer mediaPlayer1;
    static boolean bgMusic;
    static boolean soundMusic;

    public GameMusic(Context context) {
        mediaPlayer1 = MediaPlayer.create(context, R.raw.game);
        mediaPlayer1.setLooping(true);
        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        soundmap.put(1, soundPool.load(context, R.raw.eat, 1));
        soundmap.put(2, soundPool.load(context, R.raw.over, 1));
        soundmap.put(3, soundPool.load(context, R.raw.btn, 1));
        saved = PreferenceManager.getDefaultSharedPreferences(context);
    }
    public void startMusic(int id) {
        bgMusic =saved.getBoolean("bgmusic",true);
        soundMusic =saved.getBoolean("soundmusic",true);

            switch (id) {
                case GAME_MUSIC:
                    if (bgMusic) {
                        mediaPlayer1.start();
                    }
                    break;

                case EAT_MUSIC:
                    if (soundMusic) {
                        soundPool.play(soundmap.get(1), 1, 1, 0, 0, 1);
                        break;
                    }
                case OVER_MUSIC:
                    if (soundMusic) {
                        soundPool.play(soundmap.get(2), 1, 1, 0, 0, 1);
                        break;
                    }
                case BTN_MUSIC:
                        soundPool.play(soundmap.get(3), 1, 1, 0, 0, 1);
                    break;
            }

        }

    public void stopGameMusic() {
        try {
            mediaPlayer1.stop();
            mediaPlayer1.prepare();
            mediaPlayer1.seekTo(0);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    public void pauseGameMusic(){
        mediaPlayer1.pause();
    }
    public void recycle(){
        mediaPlayer1.release();
        soundPool.release();
    }

}
